package com.czx.service.impl;

import com.czx.common.constants.RedisKeys;
import com.czx.entity.DiscussPost;
import com.czx.entity.User;
import com.czx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class PostScoreServiceImpl implements PostScoreService {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private CommentService commentService;

    /**
     * 加添帖子更新分数的value
     * @param postId
     */
    @Override
    public void addPostIdToRedis(Integer postId) {
        stringRedisTemplate.opsForSet().add(RedisKeys.POST_SCORE_KEY, postId.toString());
    }


    @Override
    public void computeScore(Integer postId) {
        //根据帖子id查询帖子信息
        DiscussPost post = discussPostService.getById(postId);
        //获取他的状态(是否加精 1加精 )
        Integer status = post.getStatus();
        //获取帖子下面的点赞数量
        Long likeCount = likeService.getLikeCount(1, postId);
        //查询帖子下面的评论数量
        Long commentCount = commentService.getCommentCountByPostId(postId);
        //查询作者信息
        User user = userService.getUserById(post.getUserId());
        //计算分数
        Long score = getScore(status, likeCount, commentCount, user);
        double postScore = Math.log(score);
        //更新帖子分数
        discussPostService.updatePostScore(postId,postScore);
    }

    /**
     * 计算分数
     * @param status
     * @param likeCount
     * @param commentCount
     * @param user
     * @return
     */
    public Long getScore(Integer status,Long likeCount,Long commentCount,User user){
        int weight = status == 1 ? 100 : 0; // 如果加精了，多个100
        int userIdLevel=3;
        Long count = (likeCount * 100) + (commentCount * 200) + weight + (userIdLevel * 50);
        return  count;
    }
}
